#include <iostream>
#include <unistd.h>
#include <fcntl.h>
int main()
{
    //设置为非阻塞：将文件描述符设置为非阻塞
    int fl = fcntl(0,F_GETFL);
    if(fl<0)
    {
        perror("fcntl");
        return 1;
    }
    fcntl(0,F_SETFL,fl|O_NONBLOCK);
    while(true)
    {
        std::string tips = "Please Enter# ";
        write(0,tips.c_str(),tips.size());
        char buffer[1024];
        int n = read(0,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n] = 0;
            std::cout<<buffer<<std::endl;
        }
        else if(n==0)
        {
            std::cout<<"read file end...."<<std::endl;
        }
        else
        {
            //EAGAIN和EWOULDBLOCK是一样的
            if(errno==EAGAIN|errno==EWOULDBLOCK)
            {
                std::cout<<"数据没就绪"<<std::endl;
                sleep(1);
            }
            else if(errno==EINTR)
            {
                std::cout<<"被中断,重新来"<<std::endl;
                sleep(1);
            }
            else
            {
                std::cout<<"read error, errno: "<<errno<<std::endl;
            }
        }
    }
    return 0;
}